import base64
import os
import re
import uuid
from http import HTTPStatus

import oss2
from gradio_client import utils as client_utils

__all__ = ["encode_file_to_base64", "file_path_to_oss_url", "re_rindex"]


def encode_file_to_base64(file_path):
    with open(file_path, "rb") as file:
        mime_type = client_utils.get_mimetype(file_path)
        bae64_data = base64.b64encode(file.read()).decode("utf-8")
        return f"data:{mime_type};base64,{bae64_data}"


# OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET。
auth = oss2.Auth(os.getenv("OSS_ACCESS_KEY_ID"), os.getenv("OSS_ACCESS_KEY_SECRET"))
endpoint = os.getenv("OSS_ENDPOINT")
bucket_name = os.getenv("OSS_BUCKET_NAME")
bucket = oss2.Bucket(auth, endpoint, bucket_name)


def file_path_to_oss_url(file_path: str):
    if file_path.startswith("http"):
        return file_path
    ext = file_path.split(".")[-1]
    object_name = f"{uuid.uuid4()}.{ext}"
    response = bucket.put_object_from_file(object_name, file_path)
    file_url = file_path
    if response.status == HTTPStatus.OK:
        file_url = bucket.sign_url("GET", object_name, 60 * 60, slash_safe=True)
    return file_url